package com.zk.algorithm.tree;

import com.zk.algorithm.annotation.LeetCodeExplore;
import com.zk.algorithm.annotation.Medium;

@LeetCodeExplore
@Medium
public class NumberOfIslands {

    // ================================
    // DFS
    // ================================

    public int numIslands(char[][] grid) {
        if (grid.length == 0 || grid[0].length == 0)
            return 0;

        int cnt = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    cnt++;
                    dfsMark1To0(grid, i, j);
                }
            }
        }
        return cnt;
    }

    private void dfsMark1To0(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1') {
            return;
        }

        grid[i][j] = 0;
        dfsMark1To0(grid, i + 1, j);
        dfsMark1To0(grid, i - 1, j);
        dfsMark1To0(grid, i, j - 1);
        dfsMark1To0(grid, i, j + 1);
    }

}